package io.nutz.nutzsite.module.qn.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.nutz.dao.Chain;
import org.nutz.dao.Cnd;
import org.nutz.dao.util.cri.SqlExpressionGroup;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.json.Json;
import org.nutz.lang.Lang;
import org.nutz.lang.Strings;
import org.nutz.log.Log;
import org.nutz.log.Logs;
import org.nutz.mvc.annotation.At;
import org.nutz.mvc.annotation.Ok;
import org.nutz.mvc.annotation.POST;
import org.nutz.mvc.annotation.Param;
import org.nutz.plugins.slog.annotation.Slog;

import io.nutz.nutzsite.common.base.Result;
import io.nutz.nutzsite.common.utils.DateUtils;
import io.nutz.nutzsite.common.utils.ShiroUtils;
import io.nutz.nutzsite.common.utils.StringUtils;
import io.nutz.nutzsite.module.exam.models.Qdb;
import io.nutz.nutzsite.module.exam.models.Question;
import io.nutz.nutzsite.module.exam.services.QdbService;
import io.nutz.nutzsite.module.exam.services.QuestionService;
import io.nutz.nutzsite.module.qn.models.Qnpaperdef;
import io.nutz.nutzsite.module.qn.models.Qnscores;
import io.nutz.nutzsite.module.qn.services.QnpaperdefService;
import io.nutz.nutzsite.module.qn.services.QnscoresService;
import io.nutz.nutzsite.module.sys.models.Mytask;
import io.nutz.nutzsite.module.sys.models.User;
import io.nutz.nutzsite.module.sys.services.MytaskService;
import io.nutz.nutzsite.module.sys.services.UserService;
/**
 * 问卷任务 信息操作处理
 * 
 * @author lrw
 * @date 2020-07-26
 */
@IocBean
@At("/qn/paperdef")
public class QnpaperdefController {
	private static final Log log = Logs.get();

	@Inject
	private QnpaperdefService qnpaperdefService;
	@Inject
	private QdbService qdbService;
	@Inject
	private UserService userService;
	@Inject
	private MytaskService mytaskService;
	@Inject
	private QuestionService questionService;
	@Inject
	private QnscoresService qnscoresService;
	
	@RequiresPermissions("qn:paperdef:view")
	@At("")
	@Ok("th:/qn/paperdef/qnpaperdef.html")
	public void index(HttpServletRequest req) {

	}

	/**
	 * 查询问卷任务列表
	 */
	@RequiresPermissions("qn:paperdef:list")
	@At
	@Ok("json")
	public Object list(@Param("pageNum")int pageNum,
					   @Param("pageSize")int pageSize,
					   @Param("name") String name,
					   @Param("beginTime") Date beginTime,
					   @Param("endTime") Date endTime,
					   @Param("orderByColumn") String orderByColumn,
					   @Param("isAsc") String isAsc,
					   HttpServletRequest req) {
		Cnd cnd = Cnd.NEW();
		if (!Strings.isBlank(name)){
			cnd.and("name", "like", "%" + name +"%");
		}

		return qnpaperdefService.tableList(pageNum,pageSize,cnd,orderByColumn,isAsc,null);
	}

	/**
	 * 新增问卷任务
	 */
	@At("/add")
	@Ok("th:/qn/paperdef/add.html")
	public void add( HttpServletRequest req) {
		List<Qdb> list=qdbService.query(Cnd.where("pid","=",1));
		req.setAttribute("kms", list);
	}

	/**
	 * 新增保存问卷任务
	 */
	@At
	@POST
	@Ok("json")
	@RequiresPermissions("qn:paperdef:add")
	@Slog(tag="问卷任务", after="新增保存问卷任务 id=${args[0].id}")
	public Object addDo(@Param("..") Qnpaperdef qnpaperdef,HttpServletRequest req) {
		try {
			qnpaperdef.setCreateBy(ShiroUtils.getSysUserId());
			qnpaperdef.setCreateTime(new Date());
			qnpaperdefService.insert(qnpaperdef);
			return Result.success("system.success");
		} catch (Exception e) {
			return Result.error("system.error");
		}
	}

	/**
	 * 修改问卷任务
	 */
	@At("/edit/?")
	@Ok("th:/qn/paperdef/edit.html")
	public void edit(String id, HttpServletRequest req) {
		Qnpaperdef qnpaperdef = qnpaperdefService.fetch(id);
		req.setAttribute("paperdef",qnpaperdef);
		List<Qdb> list=qdbService.query(Cnd.where("pid","=",1));
		req.setAttribute("kms", list);
	}

    /**
     * 详情问卷任务
     */
    @At("/detail/?")
    @Ok("th:/qn/paperdef/detail.html")
    public void detail(String id, HttpServletRequest req) {
		Qnpaperdef qnpaperdef = qnpaperdefService.fetch(id);
        req.setAttribute("qnpaperdef",qnpaperdef);
    }

    /**
	 * 修改保存问卷任务
	 */
	@At
	@POST
	@Ok("json")
	@RequiresPermissions("qn:paperdef:edit")
	@Slog(tag="问卷任务", after="修改保存问卷任务")
	public Object editDo(@Param("..") Qnpaperdef qnpaperdef,HttpServletRequest req) {
		try {
			if(Lang.isNotEmpty(qnpaperdef)){
				qnpaperdef.setUpdateBy(ShiroUtils.getSysUserId());
				qnpaperdef.setUpdateTime(new Date());
				qnpaperdefService.update(qnpaperdef);
			}
			return Result.success("system.success");
		} catch (Exception e) {
			return Result.error("system.error");
		}
	}

	/**
	 * 删除问卷任务
	 */
	@At("/remove")
	@Ok("json")
	@RequiresPermissions("qn:paperdef:remove")
	@Slog(tag ="问卷任务", after= "删除问卷任务:${array2str(args[0])}")
	public Object remove(@Param("ids")String[] ids, HttpServletRequest req) {
		try {
			qnpaperdefService.delete(ids);
			return Result.success("system.success");
		} catch (Exception e) {
			return Result.error("system.error");
		}
	}
	@At("/makep/?")
	@Ok("th:/qn/paperdef/addtask.html")
	public void makep(String id, HttpServletRequest req) {
		req.setAttribute("ksid", id);
		//List<Role> roles = roleService.query(Cnd.where("status", "=", false).and("del_flag", "=", false));
        //req.setAttribute("roles", roles);
        Qnpaperdef paperdef= qnpaperdefService.fetch(id);
		req.setAttribute("paperdef", paperdef);
	}
	
	/**
	 * 新增保存排考抽题
	 */
	@At
	@POST
	@Ok("json")
	@Slog(tag="生成问卷任务", after="新增问卷任务 id=${args[0].id}")
	public Object addtaskDo(@Param("..") Mytask exarrange,
			@Param("ksuser") String ksuser,
			HttpServletRequest req) {
		try {
			//=========找考生========================================
			Cnd cnd=Cnd.NEW();
			if(ksuser.length()>0){
				ksuser=StringUtils.StringToString(ksuser);
				SqlExpressionGroup e=Cnd.exps("dept_id","in",ksuser).or("classg","in",ksuser).or("id","in",ksuser);
				cnd.and(e);
			}

			List<User> users=userService.query("id", cnd);
			if(users==null || users.size()==0)return Result.error("没有指定的测评对象");
			//========找题目==========================================
			String ksid=exarrange.getKsid();
			Qnpaperdef paperdef=qnpaperdefService.fetch(ksid);
			exarrange.setStatus(0);
            exarrange.setIntro(paperdef.getIntro());
            exarrange.setName(paperdef.getName());
            exarrange.setEntryurl("qn/paperdef/goqn");
			//==========为每人抽题组卷================
			for(User u:users){
				String uid=u.getId();
	            exarrange.setUid(uid);
				try{	
					mytaskService.insert(exarrange);
				} catch (Exception e) {
					log.debug("\r\n生成【"+uid+"】的问卷失败:"+e.getMessage());
				}
			}
			
			return Result.success("system.success");
		} catch (Exception e) {
			log.debug("\r\n"+e.getMessage());
			return Result.error("system.error");
		}
	}
	@At
	@Ok("json")
	public Object goqn(HttpSession session,HttpServletRequest req){
		return Result.success("qn/paperdef/goqn2/");
	}
		
	@At("/goqn2/?")
	@Ok("th:/qn/paperdef/qning.html")
	public void goqn2(String id,HttpSession session,HttpServletRequest req){
		User user=ShiroUtils.getSysUser();
		Qnpaperdef qnpaperdef=qnpaperdefService.fetch(id);
		int kmid=qnpaperdef.getKmid();
		Cnd cnd=Cnd.NEW();
		cnd.and("qdbid", "=", kmid).asc("qtid,id");
		List<Question> qlist=questionService.query(cnd);
		
		req.setAttribute("now0", DateUtils.getDateTime());
		req.setAttribute("ksid",id);
		req.setAttribute("qlist",qlist);
		req.setAttribute("user",user);
		int n=0;
		for(int i=0;i<qlist.size();i++){
			if(qlist.get(i).getQtid()<5) n++;
		}		
		req.setAttribute("total",n);
	}
	@At
	@POST
	@Ok("json")
	@Slog(tag="提交", after="问卷完成：${args[0]}")
	public Object saveScores(@Param("ksid")String ksid,@Param("data") String obs,HttpServletRequest req) {
		User u=ShiroUtils.getSysUser();
		Cnd cnd=Cnd.NEW();
		cnd.and("ksid", "=", ksid).and("uid", "=", u.getId());
		try {
			List<Qnscores> sc=qnscoresService.query( cnd);
			if(sc.size()>0)return Result.error("您已完成了此次问卷调查");//不允许刷新网页重新提交
			
			List<Question> qlist=Json.fromJsonAsList(Question.class, obs);
			//Map<Integer,String> ansmap=qlist.stream().collect(Collectors.toMap(Question::getId, Question::getQans, (key1, key2) -> key2));
			List<Qnscores> qnscores=new ArrayList<Qnscores>();
			for(Question question:qlist){
				int qid=question.getId();
				String stuans=question.getQans();
				Qnscores score=new Qnscores();
				//score.setXy(u.getXy());
				//score.setZymc(u.getZymc());
				score.setBj(u.getClassg());
				score.setKsid(ksid);
				score.setUid(u.getId());
				score.setTiid(qid);
				score.setStuans(stuans);
				score.setJjtime(new Date());
				qnscores.add(score);
			}
			qnscoresService.insert(qnscores) ;
			mytaskService.update(Chain.make("status", 2), cnd);
			log.debug(qlist.toString());
			return Result.success("您已完成此次问卷调查，再次谢谢您的支持");
		} catch (Exception e) {

			return Result.error("提交问卷时遇到错误:\r\n"+e.getMessage());
		}
	}
}
